package com.srkj.controller;

import com.srkj.entity.Product;
import com.srkj.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * com.srkj.controller
 * Created by zhangshaoxiong
 * data : 2018 17 21 17:21
 */
@Controller
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 查询所有商品
     * @param model
     * @return
     * @throws Exception
     */
    @GetMapping("/products")
    public String findProducts(Model model) throws Exception{
        return "product/list";
    }

    /**
     * 查询所有商品
     * @param model
     * @return
     * @throws Exception
     */
    @PostMapping("/findProductList")
    @ResponseBody
    public List<Product> findProductList() throws Exception{

        List<Product> all = productService.findAll();
//        model.addAttribute("products",all);
        return all;
    }

    @GetMapping("/product")
    public String toaddProducts(Model model) throws Exception{
        return "product/add";
    }
    /**
     * 新增user
     * @return
     */
    @PostMapping("/product")
    public String saveProduct(Product product) throws Exception{
       if (product != null){
           productService.saveProduce(product);
       }
        return "redirect:/products";
    }

    @DeleteMapping("/product/{pid}")
    public String deleteProduct(@PathVariable("pid") int pid) throws Exception{
        Product product = productService.findByPid(pid);
        if (product != null){
            productService.deleteProduct(pid);
        }
        return "redirect:/products";
    }




}
